<?php

namespace Dls\Entity\V0\Traits;

use Dls\Entity\V0\Grid;
use Dls\Entity\V0\Grid\Model;
use Dls\Entity\V0\Response;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

/**
 * Trait ModelForm
 * @method Grid table()
 * @package Dls\Entity\V0\Traits
 */
trait ModelForm
{
    /** 添加/编辑页渲染 */
    public function edit($id)
    {
        return $this->form()->edit($id);
    }

    /** 新增页渲染 */
    public function create()
    {
        return $this->form();
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return $this->edit($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        return $this->form()->update($id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $this->form()->destroy($id);
        return back();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        return $this->form()->store();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @deprecated 默认已经内置了
     * @throws \Exception
     */
    public function list()
    {
        $grid = $this->table()->build();
        $paginator = $grid->model()->get();

        $data = [
            'data' => $grid->model()->buildData($paginator),
            'nums' => $paginator->total(),
            'pages' => $paginator->lastPage(),
        ];

        return Response::success()->jsonp($data);
    }

}
